# Created by Gao Song on 2022-12-26
import logging
import sys
import time
from datetime import datetime

from core.constant import Direction
from core.factory import create_object
from event import EventEngine
from event.event_def import EVENT_TRADE
from fucker import FuckerStatus
from fucker.best_limit_fucker import BestLimitFucker
from mysite.lqcon.managements import AccountManagement
from mysite.lqcon.models import Position

logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
import logging


def fuck_now(target_pos):
    # logging.basicConfig(level=logging.DEBUG,
    #                     format='%(asctime)s - %(name)s[%(funcName)s] - %(levelname)s: %(message)s',
    # filename=f'd:fucker_now.log',
    # filemode='a')
    account_name = 'test_simnow01'
    account = AccountManagement.get_account_by_name(account_name)

    event_engine = EventEngine()
    event_engine.start()

    gateway = create_object('gateway', account.gateway_type, event_engine, account.name)
    gateway.connect(account.connection_info)
    logging.info('connected....')

    time.sleep(10)

    def on_trade(e):
        trade_data = e.data

        symbol = f'{trade_data.symbol}.{trade_data.exchange.value}'
        volume = trade_data.volume
        price = trade_data.price
        if trade_data.direction == Direction.SHORT:
            volume = -volume

        account.long(symbol, volume, price)

    event_engine.register(EVENT_TRADE, on_trade)

    fucker = BestLimitFucker(gateway)
    fucker.init()

    broker_pos = fucker.position_management.to_series()
    for symbol,pos in broker_pos.items():
        Position.objects.update_or_create(symbol=symbol, defaults={'account': account, 'volume': pos,
                                                                    'create_time': datetime.now()})
    pos = broker_pos.copy()
    for sym in target_pos.keys():
        pos[sym] = target_pos[sym]

    fucker.set_task(pos)
    fucker.start()

    while fucker.status not in (FuckerStatus.FINISHED, FuckerStatus.TERMINATED):
        time.sleep(10)
    logging.info('finish....')

    event_engine.stop()


if __name__ == '__main__':
    target_pos = {"AP510.CZCE": 1}

    fuck_now(target_pos)
    # fuck_now('test_pa880',{'sn2303.SHFE':1})
